<?php

namespace app\common\model;
use think\Model;
use think\Db;
use think\Paginator;


/**
 * 会员余额日志模型
 */
class MoneyLog extends Model {
   
    // 表名
    protected $name = 'user_money_log';

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = '';
    // 追加属性
    protected $append = [];
    protected $resultSetType = 'collection';

    /**
     * 更新用户余额
     */
    public function saveUserMoney($change_type, $type, $user_id, $money, $memo = '',$video_id ="0")
    {
        //查询当前用户信息
        $userInfo = Db::name('user')->where('id', $user_id)->find();

        if (!$userInfo) return false;
        // 启动事务
        Db::startTrans();
        try {
            //添加会员余额记录
            $userMoneyLog['type'] = $type;
            $userMoneyLog['user_id'] = $user_id;
            $userMoneyLog['change_type'] = $change_type;
            $userMoneyLog['money'] = $money;
            $userMoneyLog['before'] = $userInfo['money'];
            $userMoneyLog['memo'] = $memo;
            $userMoneyLog['video_id'] = $video_id ? $video_id : "0"; 
            if ($change_type == 1) {
                $userMoneyLog['after'] = $userInfo['money'] + (float)$money;

                $userMoneyRes = Db::name('user')->where('id', $user_id)->setInc('money', (float)$money);
            } else {
                $userMoneyLog['after'] = $userInfo['money'] - (float)$money;

                $userMoneyRes = Db::name('user')->where('id', $user_id)->setDec('money', (float)$money);
            }
            //用户余额变动失败
            if (!$userMoneyRes) return false;
            //添加用户余额记录
            $moneyLogRes = $this->save($userMoneyLog);
            //用户余额记录添加失败
            if (!$moneyLogRes) return false;
            //事务提交
            Db::commit();

            return true;
        } catch (\think\Exception\DbException $e) {
            // 回滚事务
            Db::rollback();

            return false;
        }
    }

    public static function systemPage(array $where) {

        $model = new self;
        $count = self::where('type', $where['type'])->where('user_id', $where['uid'])->count();
        $list = $model->where('type', $where['type'])->where('user_id', $where['uid']);
        $list = $model->page((int) $where['page'], (int) $where['limit'])->order('createtime', 'desc')->select();
         //$list = $model->paginate((int) $where['limit'], false, ['page' => (int) $where['page']]);
       // echo $model->getLastSql();exit;
        
        $list = $list ? $list->toArray() : [];
        return compact("list", "count");
    }


}
